<?php
/**
 * @author wyl
 * @date 2015-10-27 09:23:40
 */
Yii::import('dao.bidAuction.AuctionLimitDao');
class AutoBidForm extends CFormModel{
	public $customer_id;
	public $auction_id;
	public $amount;
	public $end_time;
	public $start_price;
	
	public function rules(){
		return array(
			array('customer_id,auction_id,amount,end_time','required'),	
			array('amount','numerical','integerOnly'=>true,'min'=>1),
		    array('start_price','numerical','min'=>0),
			array('amount','hasEnoughBids'),
			//array('customer_id','hasAutobid'),
		    array('customer_id','hasBuyitnowLimit'),
		);
	}

	public function hasBuyitnowLimit($attribute,$params){
    	    $limit=new AuctionLimitDao();
    		$limit->customerId=$this->customer_id;
    		$limit->auctionId=$this->auction_id;
    		$search=array(
    		      'type'=>'BUY_IT_NOW',
    		      'auction'=>$this->auction_id
    		);
    		$limitNum=$limit->limit($search);
    		if ($limitNum>=1) {
    			$this->addError($attribute, 'You have buy it now!');
    		}   
	}
	
	public function hasAutobid($attribute,$params){
    		$autobid=new Autobid();
    		$autobid=$autobid->findAllByAttributes(array(
    				'customer_id'=>$this->customer_id,
    		));	
    		if (count($autobid)>=2) {
    			$this->addError('hasLimit', "You can't open autobid greater than two!");
    		}
	}
	
	public function hasEnoughBids($attribute,$params){
    		$money=new CDbCriteria();
    		$money->select='bid_num';
    		$money->compare('customer_id', $this->customer_id);
    		$money=CustomerBidInfo::model()->findAll($money);
    		$total=0;
    		if (!empty($money)) {
    			foreach ($money as $m){
    				$total+=$m->bid_num;
    			}
    			if($total<$this->amount){
    				$this->addError($attribute, 'You can not load more bids in the auto bidder than you have in your bid account!');
    			}
    		}
	}
	
	public function hasAutobidLimit(){
	    $auctions=new AuctionLimit();
	    $criteria=new CDbCriteria();
	    $criteria->compare('winner_id', $this->customer_id);
	    $criteria->addCondition('end_time>='.time());
	    $criteria->compare('limit_type', 'AUTO_BID');
	    $auctions=$auctions->findAll($criteria);
	    $autoBidNum=0;
	    if (!empty($auctions)){
	        $autoBidNum=count($auctions);
	    }
	    return $autoBidNum>0;
	}
	
	public function limitExists($attribute,$params){
    		$limit=new AuctionLimitDao();
    		$limit->customerId=$this->customer_id;
    		$limit->auctionId=$this->auction_id;
    		$limitNum=$limit->limit();
    		if ($limitNum>=3) {
                  $this->addError($attribute, "Your limits is overflow!");
    		} 
	}
	
	public function autobidExists($attribute,$params){
    		$autobid=new Autobid();
    		$autobid=$autobid->findAllByPk($this->auction_id.':'.$this->customer_id);
    		if(!empty($autobid)){
    			$this->addError($attribute, 'There is no autobid exists');
    		}	
	}
}